package cn.tedu.order.service;

import cn.tedu.order.entity.AccountMessage;
import cn.tedu.order.entity.Order;
import cn.tedu.order.entity.TxInfo;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.mapper.TxMapper;
import cn.tedu.order.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.transaction.xa.Xid;
import java.util.Random;
import java.util.UUID;
@RocketMQTransactionListener
@Service
@Slf4j
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private TxMapper txMapper;

    // 业务方法中，不直接执行业务处理
    // 而是发送事务消息
    @Override
    public void create(Order order) {
        // 如果有标签，格式orderTopic:tag1
        //执行监听器需要的业务数据参数:order
        String xid = UUID.randomUUID().toString().replace("-", "");
        // AccountMessage封装数据
        AccountMessage am =
                new AccountMessage(order.getUserId(), order.getMoney(), xid);
        // 转成json
        String json = JsonUtil.to(am);
        // json再封装到 spring 的通用message
        Message<String> msg = MessageBuilder.withPayload(json).build();

        rocketMQTemplate.sendMessageInTransaction(
                "orderTopic",msg,order);
    }
    // 完成业务处理的方法

    public void doCreate(Order order) {
        //远程调用发号器生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);
        // 临时随机生成一个id,添加发号器后这行代码删除
        order.setId(orderId);
        orderMapper.create(order);

        // 调用库存减少商品库存
//        storageClient.decrease(order.getProductId(), order.getCount());
        // 调用账户减少账户金额
//        accountClient.decrease(order.getUserId(), order.getMoney());
    }
    // 执行本地事务
    // rocketMQTemplate.sendMessageInTransaction(
    //         "orderTopic", msg, 执行监听器需要的业务数据参数/order);
    @Transactional
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(
            Message message, Object o) {
        // 存储到数据表的状态值 用 0,1表示  成功0 失败1
        int status;
        // 返回的事务状态是status 对象
        RocketMQLocalTransactionState state;
        try {
            // 执行原来的业务代码
            Order order = (Order) o;
            System.out.println("执行本地事务");
            doCreate(order);
            Thread.sleep(70*1000);

            status = 0;
            state = RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            log.error("本地事务存储订单失败",e);
            status = 1;
            state = RocketMQLocalTransactionState.ROLLBACK;

        }
        // 把事务状态存到tx_table
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        txMapper.insert(new TxInfo(xid,status,System.currentTimeMillis()));
        return state;
    }
    // 处理事务状态回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        System.out.println("正在处理Rocketmq服务器的事务状态回查");
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null){
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0:return RocketMQLocalTransactionState.COMMIT;
            case 1:return RocketMQLocalTransactionState.ROLLBACK;
            default:return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
